package cn.chiship.framework.upms.biz.user.service.impl;

import cn.chiship.framework.common.constants.CommonCacheConstants;
import cn.chiship.framework.common.util.FrameworkUtil2;
import cn.chiship.framework.upms.biz.user.entity.*;
import cn.chiship.framework.upms.biz.user.mapper.UpmsPermissionApiMapper;
import cn.chiship.framework.upms.biz.user.pojo.dto.UpmsUserOrganizationDto;
import cn.chiship.framework.upms.biz.user.pojo.vo.UpmsOrganizationUserVo;
import cn.chiship.framework.upms.biz.user.service.UpmsUserOrganizationService;
import cn.chiship.sdk.cache.service.RedisService;
import cn.chiship.sdk.core.base.constants.BaseCacheConstants;
import cn.chiship.sdk.core.exception.custom.BusinessException;
import cn.chiship.sdk.core.util.ObjectUtil;
import cn.chiship.sdk.core.util.StringUtil;
import cn.chiship.sdk.framework.base.BaseServiceImpl;
import cn.chiship.framework.upms.biz.user.mapper.UpmsUserOrganizationMapper;

import javax.annotation.Resource;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 用户组织关联表业务接口实现层 切记不要使用UpmsOrganizationService及UpmsUserService，避免互相调用 2021/9/27
 *
 * @author lijian
 */
@Service
public class UpmsUserOrganizationServiceImpl extends BaseServiceImpl<UpmsUserOrganization, UpmsUserOrganizationExample>
		implements UpmsUserOrganizationService {

	@Resource
	UpmsUserOrganizationMapper upmsUserOrganizationMapper;

	@Resource
	UpmsPermissionApiMapper upmsPermissionApiMapper;

	@Resource
	RedisService redisService;

	@Override
	public List<JSONObject> selectUserOrg(String userId) {
		List<JSONObject> result = new ArrayList<>();
		List<UpmsOrganizationUserVo> organizationUserVos = upmsPermissionApiMapper.selectOrganizationByUserId(userId);
		for (UpmsOrganizationUserVo organizationUserVo : organizationUserVos) {
			JSONObject json = JSON.parseObject(JSON.toJSONString(organizationUserVo));
			getParentInfoByTreeNumber(organizationUserVo.getTreeNumber(), json);
			result.add(json);
		}
		return result;
	}

	/**
	 * 凡是保存用户与组织关联关系的业务均调用此方法
	 * @param upmsUserOrganizationDto
	 */
	@Override
	public void saveUserOrganization(UpmsUserOrganizationDto upmsUserOrganizationDto) {
		if (StringUtil.isNullOrEmpty(upmsUserOrganizationDto.getUserId())) {
			throw new BusinessException("关联组织时，用户为空！");
		}
		UpmsUserOrganizationExample userOrganizationExample = new UpmsUserOrganizationExample();
		userOrganizationExample.createCriteria().andUserIdEqualTo(upmsUserOrganizationDto.getUserId())
				.andOrganizationIdEqualTo(upmsUserOrganizationDto.getOrganizationId());
		List<UpmsUserOrganization> userOrganizations = upmsUserOrganizationMapper
				.selectByExample(userOrganizationExample);
		if (userOrganizations.isEmpty()) {
			UpmsUserOrganization upmsUserOrganization = new UpmsUserOrganization();
			upmsUserOrganization.setUserId(upmsUserOrganizationDto.getUserId());
			upmsUserOrganization.setOrganizationId(upmsUserOrganizationDto.getOrganizationId());
			upmsUserOrganization.setJob(upmsUserOrganizationDto.getJob());
			upmsUserOrganization.setPhone(upmsUserOrganizationDto.getPhone());
			upmsUserOrganization.setOrders(upmsUserOrganizationDto.getOrders());
			super.insertSelective(upmsUserOrganization);
		}
		else {
			UpmsUserOrganization upmsUserOrganization = userOrganizations.get(0);
			upmsUserOrganization.setJob(upmsUserOrganizationDto.getJob());
			upmsUserOrganization.setPhone(upmsUserOrganizationDto.getPhone());
			upmsUserOrganization.setOrders(upmsUserOrganizationDto.getOrders());
			upmsUserOrganizationMapper.updateByPrimaryKeySelective(upmsUserOrganization);
		}
	}

	@Override
	public Boolean validateExist(String userId, String orgId) {
		UpmsUserOrganizationExample userOrganizationExample = new UpmsUserOrganizationExample();
		userOrganizationExample.createCriteria().andUserIdEqualTo(userId).andOrganizationIdEqualTo(orgId);
		return upmsUserOrganizationMapper.countByExample(userOrganizationExample) > 0;
	}

	/**
	 * 凡是组装机构层级全部调用该方法 为何将此方法此业务层而不是组织业务层，是因为 避免两个业务层互相调用
	 * @param treeNumber
	 * @param json
	 * @return
	 */
	@Override
	public JSONObject getParentInfoByTreeNumber(String treeNumber, JSONObject json) {
		if (StringUtil.isNullOrEmpty(treeNumber)) {
			return json;
		}
		List<String> treeNumbers = FrameworkUtil2.getAllParentTreeNumber(treeNumber);
		String key = CommonCacheConstants.buildKey(BaseCacheConstants.REDIS_ORG_PREFIX);
		List<String> orgIds = new ArrayList<>();
		List<String> orgNames = new ArrayList<>();
		for (String tree : treeNumbers) {
			UpmsOrganization organization = (UpmsOrganization) redisService.hget(key, tree);
			if (ObjectUtil.isNotEmpty(organization)) {
				orgIds.add(organization.getId());
				orgNames.add(organization.getOrganizationName());
			}

		}

		json.put("_fullOrgIds", orgIds);
		json.put("_fullOrgNames", orgNames);
		json.put("_fullOrgId", StringUtil.join(orgIds, ","));
		json.put("_fullOrgName", StringUtil.join(orgNames, "/"));
		return json;
	}

	@Override
	public String getParentOrgIdByTreeNumber(String treeNumber) {
		JSONObject json = new JSONObject();
		getParentInfoByTreeNumber(treeNumber, json);
		return json.getString("_fullOrgId");
	}

	@Override
	public String getParentOrgNameByTreeNumber(String treeNumber) {
		JSONObject json = new JSONObject();
		getParentInfoByTreeNumber(treeNumber, json);
		return json.getString("_fullOrgName");
	}

	@Override
	public List<String> listOrgIdByTreeNumber(String treeNumber) {
		Set<String> orgIds = new TreeSet<>();
		String key = CommonCacheConstants.buildKey(BaseCacheConstants.REDIS_ORG_PREFIX);
		Map<Object, Object> map = redisService.hget(key);
		for (Map.Entry<Object, Object> entry : map.entrySet()) {
			UpmsOrganization organization = (UpmsOrganization) entry.getValue();
			if (organization.getTreeNumber().startsWith(treeNumber)) {
				orgIds.add(organization.getId());
			}
		}
		return new ArrayList<>(orgIds);
	}

}
